package com.example.moonshine.baidumap.View.Activity;

import android.content.Intent;
import android.graphics.Color;

import android.os.Bundle;
import android.os.Handler;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.moonshine.baidumap.Entity.TaskInfoData;
import com.example.moonshine.baidumap.Entity.TaskInfoRrsultData;
import com.example.moonshine.baidumap.Service.MainService;
import com.example.moonshine.baidumap.Util.HttpUtil;
import com.example.moonshine.baidumap.Util.UrlHttpData;
import com.example.moonshine.baidumap.Util.publicUtil;
import com.example.moonshine.baidumap.View.Fragment.FirstFragment;
import com.example.moonshine.baidumap.View.Fragment.SecondFragment;
import com.example.moonshine.baidumap.R;
import com.example.moonshine.baidumap.View.Service.TaskAcceptanceService;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    // 初始化顶部栏显示

    // 定义4个Fragment对象
    private FirstFragment fg1;
    private SecondFragment fg2;
    // 帧布局对象，用来存放Fragment对象
    // 定义每个选项中的相关控件
    private RelativeLayout firstLayout;
    private RelativeLayout secondLayout;
    private ImageView firstImage;
    private ImageView secondImage;

    private TextView firstText;
    private TextView secondText;

    // 定义几个颜色
    private int whirt = 0xFFFFFFFF;
    private static boolean exit = false;

    // 定义FragmentManager对象管理器
    String index;
    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        initView(); // 初始化界面控件

        index = getIntent().getStringExtra("index");
        if (index != null) {
            setChioceItem(Integer.parseInt(index));
        } else {
            setChioceItem(0); // 初始化页面加载时显示第一个选项卡
//            setUser();
        }
        SeeTask();
    }



    /**
     * 初始化页面
     */
    private void initView() {
// 初始化底部导航栏的控件
        firstImage = (ImageView) findViewById(R.id.first_image);
        secondImage = (ImageView) findViewById(R.id.second_image);
        firstText = (TextView) findViewById(R.id.first_text);
        secondText = (TextView) findViewById(R.id.second_text);

        firstLayout = (RelativeLayout) findViewById(R.id.first_layout);
        secondLayout = (RelativeLayout) findViewById(R.id.second_layout);
        firstLayout.setOnClickListener(MainActivity.this);
        secondLayout.setOnClickListener(MainActivity.this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.first_layout:
                setChioceItem(0);
                break;
            case R.id.second_layout:
                setChioceItem(1);
                break;
            default:
                break;
        }
    }

    /**
     * 设置点击选项卡的事件处理
     *
     * @param index 选项卡的标号：0, 1, 2, 3
     */
    private void setChioceItem(int index) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        clearChioce(); // 清空, 重置选项, 隐藏所有Fragment
        hideFragments(fragmentTransaction);
        switch (index) {
            case 0:
                firstImage.setImageResource(R.drawable.ic_shouye);
                firstText.setTextColor(whirt);
                firstLayout.setBackgroundColor(Color.parseColor("#0a1720"));
                UltimateBar.newColorBuilder()
                        .statusColor(Color.parseColor("#003768"))       // 状态栏颜色
                        .statusDepth(50)                // 状态栏颜色深度
                        .build(this)
                        .apply();
// 如果fg1为空，则创建一个并添加到界面上
                if (fg1 == null) {
                    fg1 = new FirstFragment();
                    fragmentTransaction.add(R.id.content, fg1);
                } else {
// 如果不为空，则直接将它显示出来
                    fragmentTransaction.show(fg1);
                }
                break;
            case 1:
                secondImage.setImageResource(R.drawable.ic_geren);
                secondText.setTextColor(whirt);
                secondLayout.setBackgroundColor(Color.parseColor("#0a1720"));
                UltimateBar.newColorBuilder()
                        .statusColor(Color.parseColor("#253847"))       // 状态栏颜色
                        .statusDepth(50)                // 状态栏颜色深度
                        .build(this)
                        .apply();
                if (fg2 == null) {
                    fg2 = new SecondFragment();
                    fragmentTransaction.add(R.id.content, fg2);
                } else {
                    fragmentTransaction.show(fg2);
                }
                break;
        }
        fragmentTransaction.commit(); // 提交
    }

    /**
     * 当选中其中一个选项卡时，其他选项卡重置为默认
     */
    private void clearChioce() {

        firstImage.setImageResource(R.drawable.ic_shouye1);
        firstText.setTextColor(Color.parseColor("#0a1720"));
        firstLayout.setBackgroundColor(whirt);
        secondImage.setImageResource(R.drawable.ic_geren1);
        secondText.setTextColor(Color.parseColor("#0a1720"));
        secondLayout.setBackgroundColor(whirt);
    }

    /**
     * 隐藏Fragment
     *
     * @param fragmentTransaction
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        if (fg1 != null) {
            fragmentTransaction.hide(fg1);
        }
        if (fg2 != null) {
            fragmentTransaction.hide(fg2);
        }

    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exits();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exits() {
        if (!exit) {
            exit = true;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            //利用handle延迟发送更改状态信息
            new Handler().sendEmptyMessageDelayed(0, 3000);
        } else {
            finish();
            System.exit(0);
        }
    }

//    }

    /**
     * 设置延迟
     *
     * @param ms
     */
    public static void delay(int ms) {
        try {
            Thread.currentThread();
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * 请求数据
     */
    public void SeeTask(){
        publicUtil publicUtil = new publicUtil();
        final HttpUtil httpUtil = new HttpUtil();
        final UrlHttpData urlHttpData = new UrlHttpData();
        final MainService mainService = new MainService();
        final String name = publicUtil.getUserInfo(MainActivity.this,"username","login");
        final String token = publicUtil.getUserInfo(MainActivity.this,"token","token");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String relust = httpUtil.getPostTask(name,token,urlHttpData.seeTaskUrl);
                Gson gson = new Gson();
//                TaskInfoData taskInfoData = gson.fromJson(relust,TaskInfoData.class);
                TaskInfoRrsultData taskInfoData = gson.fromJson(relust,TaskInfoRrsultData.class);
//                if (taskInfoData.getTaskInfo()==null){
//
//                    mainService.sendBroadcast("0",MainActivity.this);
//                }{
//                    mainService.sendBroadcast("1",MainActivity.this);
//                }
            }
        }).start();

//        TaskInfoRrsultData taskInfoRrsultData = gson.fromJson(relust,TaskInfoRrsultData.class)
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("MainActivity", "销毁");
    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.d("MainActivity", "隐藏");

    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.d("MainActivity", "显示");
    }


    @Override
    protected void onResume() {
        super.onResume();
        MainService mainService = new MainService();

        Log.d("MainActivity", "聚焦");
        //调用查看是否开启GPS
        mainService.openGps(MainActivity.this);
        Intent intent = new Intent(MainActivity.this,TaskAcceptanceService.class);
        startService(intent);
    }
}

